package com.woniuxy.cloud.userassembly.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.userassembly.entity.Role;
import com.woniuxy.cloud.userassembly.entity.RoleResources;
import com.woniuxy.cloud.userassembly.entity.SysResource;
import com.woniuxy.cloud.userassembly.entity.UserRole;
import com.woniuxy.cloud.userassembly.exception.UserException;
import com.woniuxy.cloud.userassembly.mapper.RoleResourcesMapper;
import com.woniuxy.cloud.userassembly.param.SaveRoleResourcesParam;
import com.woniuxy.cloud.userassembly.service.RoleResourcesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.cloud.userassembly.service.RoleService;
import com.woniuxy.cloud.userassembly.service.SysResourceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 周川雄
 * @since 2022-01-26
 */
@Service
public class RoleResourcesServiceImpl extends ServiceImpl<RoleResourcesMapper, RoleResources> implements RoleResourcesService {

    @Resource
    private RoleService roleService;
    @Resource
    private SysResourceService sysResourceService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveRoleResources(SaveRoleResourcesParam arp) {
        //先判断角色是否存在
        Role role = roleService.getOne(new QueryWrapper<Role>()
                .eq("role_id", arp.getRoleId())
                .eq("role_status", 0));

        if (StringUtils.isEmpty(role)) throw new UserException("该用户不存在", 10701);
        //清空该角色的关联表
        remove(new QueryWrapper<RoleResources>().eq("role_id", arp.getRoleId()));
        //当不勾选任何角色，只勾选账户
        if (arp.getList() == null || arp.getList().size() == 0) return true;


        //获取所有可以勾选的角色
        List<SysResource> list = sysResourceService.list(new QueryWrapper<SysResource>().in("resources_id", arp.getList()));
        System.out.println(list);
        System.out.println(list.size());
        System.out.println(arp.getList().size());
        if (list.size() != arp.getList().size()) throw new UserException("授权失败，勾选的接口数据不对", 10702);

        List<RoleResources> roleResourcesList = arp.getList().stream().map(
                id -> {
                    RoleResources war = new RoleResources();
                    war.setRoleId(arp.getRoleId());
                    war.setResourcesId(id);
                    return war;
                }).collect(Collectors.toList());
        return saveBatch(roleResourcesList);
    }
}
